package com.xstudio.pvzreborn.sound;

import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.sounds.AbstractTickableSoundInstance;
import net.minecraft.core.BlockPos;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.boss.wither.WitherBoss;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

@OnlyIn(Dist.CLIENT)
public class SoulMusic extends AbstractTickableSoundInstance {

    private static final Player player = Minecraft.getInstance().player;
    private WitherBoss wither;

    private SoulMusic(WitherBoss wither) {
        super(SoundManager.getSoundEvent("soul"), SoundSource.MUSIC);
	    this.wither = wither;
        this.looping = true;
        BlockPos pos = wither.getOnPos();
        this.x = pos.getX();
        this.y = pos.getY();
        this.z = pos.getZ();
    }

    public static void play(WitherBoss wither) {
        Minecraft.getInstance().getSoundManager().play(new SoulMusic(wither));
    }

    @Override
    public void tick() {
        // 如果凋灵死亡或者远离目标 32 格就停止播放
        if (wither != null && (!wither.isAlive() || wither.distanceToSqr(player) > 1225)) {
            this.stop();
            wither = null;
        }
    }

}
